﻿using System;
using System.IO;
using System.Net;

namespace csharp_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 应用账号（请替换为真实账号）
            string appKey = "appKey";
            // 应用密码（请替换为真实密码）
            string appSecret = "appSecret";

            // api链接
            string api = "https://api.xiaoxiangdaili.com/ip/get?appKey=" + appKey + "&appSecret=" + appSecret + "&cnt=1&wt=text";

            // 请求api链接获取代理ip
            string proxyAddr = string.Empty;
            HttpWebRequest apiReq = (HttpWebRequest)WebRequest.Create(api);
            apiReq.Method = "GET";
            HttpWebResponse apiResp = (HttpWebResponse)apiReq.GetResponse();
            using (StreamReader reader = new StreamReader(apiResp.GetResponseStream()))
            {
                proxyAddr = reader.ReadToEnd();
            }

            // 要访问的目标网页
            string page_url = "https://httpbin.org/ip";

            // 构造请求
            HttpWebRequest targetReq = (HttpWebRequest)WebRequest.Create(page_url);
            targetReq.Method = "GET";

            // 设置代理 <私密/独享代理&未添加白名单>
            WebProxy proxy = new WebProxy();
            proxy.Address = new Uri(String.Format("http://" + proxyAddr));
            proxy.Credentials = new NetworkCredential(appKey, appSecret);
            targetReq.Proxy = proxy;

            // 请求目标网页
            HttpWebResponse targetResp = (HttpWebResponse)targetReq.GetResponse();
            Console.WriteLine((int)targetResp.StatusCode);  // 获取状态码

            using (StreamReader reader = new StreamReader(targetResp.GetResponseStream()))
            {
                string str = reader.ReadToEnd();
                Console.WriteLine(str);
            }
        }
    }
}
